package cn.itrigger.mojos;

import cn.itrigger.config.VersionConfig;
import cn.itrigger.config.VersionLevelEnum;
import cn.itrigger.publish.DailyVersionPublish;
import cn.itrigger.publish.VersionPublish;
import cn.itrigger.utils.GitOperatorUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.util.logging.Logger;

/**
 *
 */
@Mojo(name = "daily")
public class ItriggerDailyMojo
extends ItriggerMojo {

    //版本号的后缀
    @Parameter(property = "dailySubffix", defaultValue = "-SNAPSHOT")
    protected String dailySubffix;
    //uat环境默认不需要打标签
    @Parameter(property = "tag", readonly = true, defaultValue = "false")
    private String tag;

    private Logger logger = Logger.getLogger("snapshot");

    public void execute() throws MojoExecutionException, MojoFailureException {

        if (BooleanUtils.toBoolean(help)) {
            help();
            return;
        }
        System.out.println("开始发布daily版本");
        GitOperatorUtils.checkout(dailyBranch);
        GitOperatorUtils.pull(dailyBranch);
//        GitOperatorUtils.clean();
        GitOperatorUtils.reset();
        validate();

        String[] diff = GitOperatorUtils.diff();
        if (null == diff || diff.length == 0){

            VersionConfig.VersionConfigBuilder builder = new VersionConfig.VersionConfigBuilder();
            VersionConfig config = null;
            try {
                config = builder.setNexusUrl(nexusUrl).setGitUrl(gitUrl).setEnv(env)
                        .setDailyBranch(dailyBranch).setTag(tag).setProject(project)
                        .setVersionLevel(VersionLevelEnum.index(Integer.parseInt(versionLevel) - 1))
                        .setDailySubffix(dailySubffix).setUatSubffix(uatSubffix).setProdSubffix(prodSubffix)
                        .setUserName(userName).setUserEmail(userEmail)
                        .setPassword(password).setName(name).setModule(module)
                        .setUpdateVersion(updateVersion).setDeploy(deploy).hasInstall(hasInstall)
                        .build();
            }catch (Exception e) {
                e.printStackTrace();
            }

            VersionPublish publish = new DailyVersionPublish(config);
            publish.publish();

        }else {
            System.err.println("本地代码有修改，无法发布版本");
        }

    }

    @Override
    public void validate() throws MojoExecutionException {
        String version = project.getVersion();

        if (!StringUtils.endsWith(version,dailySubffix)) {
            System.err.println("daily版本必须-SNAPSHOT结尾");
            throw new MojoExecutionException("daily版本必须-SNAPSHOT结尾");
        }
    }
}
